<template>
  <el-dialog
    class="listEditDialog"
    :title="$t('选择节目')"
    :visible="visible"
    width="1110px"
    :close-on-click-modal="false"
    @update:visible="updateVisible"
    append-to-body
  >
    <div class="wrap-box">
      <!-- 素材区 -->
      <div class="left">
        <!-- 搜索栏 -->
        <div class="search-row">
          <div class="search-item mr-15">
            <span class="search-item-title">{{ $t('播放编辑列表') }}</span>
            <span class="search-item-label">{{ $t('名称') }}</span>
            <el-input
              v-model="searchVal"
              size="mini"
              class="input-165"
              maxlength="20"
              autocomplete="off"
              :show-word-limit="false"
              clearable
            ></el-input>
          </div>
          <el-button @click="searchHandle" size="mini" type="primary">{{
            $t('搜索')
          }}</el-button>
        </div>
        <div class="picker-box">
          <!-- 目录树 -->
          <div class="menu-box">
            <media-menu-tree
              :is-no-action="true"
              :tree-loading="treeLoading"
              :default-checked-keys="defaultCheckedKeys"
              :context-menu-data="contextMenuData"
              @currentNodeData="currentNodeDataChange"
              :api-obj="menuApiObj"
              :api-type="'3'"
              where="inner"
            />
          </div>
          <!-- 素材缩略图 -->
          <div class="photo-box" @contextmenu="photoBoxContext">
            <mini-panel
              ref="miniPanel"
              :context-menus="miniContextMenus"
              :datas="mediaData"
              :options="{
                noPop: true,
                sizeType: 'small',
              }"
              @contextMenuClicked="miniContextMenuClicked"
              @dbClick="addRow"
            ></mini-panel>
          </div>
        </div>
        <!-- 分页部分 -->
        <div class="pag-box">
          <pagination
            layout="total, sizes, prev, pager, next"
            :page-count="3"
            :total="page.total"
            :page="page.current"
            :limit="page.size"
            @pagination="pageChange"
          ></pagination>
        </div>
      </div>
      <!-- 操作按钮区 -->
      <div class="center">
        <el-button size="small" class="caretbtn" @click="ctrl('add')" :title="$t('添加')">
          <i class="el-icon-plus" style="font-size: 12px; color: #666"></i>
        </el-button>
        <el-button size="small" class="caretbtn" @click="ctrl('remove')" :title="$t('移除')">
          <i class="el-icon-minus" style="font-size: 12px; color: #666"></i>
        </el-button>
        <template v-if="requestOpts.corpCode == requestOpts.runCorpCode">
          <el-button size="small" class="caretbtn" @click="ctrl('replace')" :title="$t('替换')">
            <i class="el-icon-refresh" style="font-size: 12px; color: #666"></i>
          </el-button>
        </template>
        <el-button size="small" icon="el-icon-top" @click="ctrl('up')" :title="$t('上移')"></el-button>
        <el-button size="small" icon="el-icon-bottom" @click="ctrl('down')" :title="$t('下移')"></el-button>
        <el-button size="small" type="primary" @click="ctrl('ok')">{{ $t('确定') }}</el-button>
        <el-button size="small" @click="ctrl('cancel')">{{ $t('取消') }}</el-button>
      </div>

      <!-- 列表区 -->
      <div class="right">
        <div class="list-title-row">
          {{ $t('播放列表') }} 
          <template v-if="requestOpts.corpCode == requestOpts.runCorpCode">
            <el-upload
              class="button-row"
              action="#"
              :show-file-list="false"
              :auto-upload="false"
              :file-list="uploadList"
              :on-change="handleUploadFile"
            >
              <el-button size="small" type="primary">{{
                $t('导入excel')
              }}</el-button>
            </el-upload>
          </template>
        </div>
        <div class="list-area">
          <list
            height="100%"
            ref="list"
            v-if="self_list"
            :highlight="true"
            :has-select="true"
            :showIndex="true"
            :list-data="self_list"
            :list-cols="listCols"
            :action-opts="actionOpts"
            @cell-double-click="removeRow"
          >
            <div
              @dblclick.stop="() => {}"
              slot="startTimeSlot"
              slot-scope="{ row }"
            >
              <input-hms type="inner" v-model="row.startTime" />
            </div>
            <div
              @dblclick.stop="() => {}"
              slot="endTimeSlot"
              slot-scope="{ row }"
            >
              <input-hms type="inner" v-model="row.endTime" />
            </div>
            <div
              @dblclick.stop="() => {}"
              slot="prioritySlot"
              slot-scope="{ row }"
            >
              <el-select v-model="row.priority">
                <el-option
                  v-for="op in priorityArray"
                  :key="op.value"
                  :value="op.value"
                  :label="$t(op.name)"
                ></el-option>
              </el-select>
            </div>
          </list>
        </div>
      </div>
    </div>

    <show-dialog
      id="inner"
      :visible.sync="showDialog.show"
      :form="showDialog.form"
      :append-to-body="true"
      op-type="4"
    ></show-dialog>

    <preview-dialog
      :append-to-body="true"
      :is-show-type="true"
      :visible.sync="previewDialog.show"
      :pre-data="previewDialog.preData"
    />
  </el-dialog>
</template>

<script>
import MiniPanel from '../../components/MiniPanel'
import List from '@/components/List'
import MediaMenuTree from '../../components/MediaMenuTree'
import Pagination from '@/components/Pagination'
import ShowDialog from '../../media-mkshow/components/ShowDialog'
import PreviewDialog from '../../components/PreviewDialog'
import InputHms from '../../media-center/components/InputHms'
import { listCtrl } from './listCtrlMixins'
import MediaApi from '@/api/media'
import { requestOpts } from '@/utils/request.js'
import { createNamespacedHelpers } from 'vuex'
const {mapActions} = createNamespacedHelpers('media')

export default {
  mixins: [listCtrl],
  components: {
    MiniPanel,
    List,
    MediaMenuTree,
    Pagination,
    ShowDialog,
    PreviewDialog,
    InputHms,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    list: {
      type: Array,
      default() {
        return []
      },
    },
  },
  data() {
    return {
      menuApiObj: {
        get: MediaApi.getCatalogue,
        bottomGet: MediaApi.getFollow,
        bottomGetList: MediaApi.getFollowCatalogue,
        getOtherMedia: MediaApi.getOtherMedia,
      },
      priorityArray: [
        { name: '缺省', value: 0 },
        { name: '普通', value: 1 },
        { name: '优先', value: 2 },
        { name: '急迫', value: 3 },
      ],
      // 目录树
      treeLoading: false,
      defaultCheckedKeys: [],
      contextMenuData: [],

      activeId: '', // 当前素材模版
      mediaData: [],
      listCols: [
        { label: '开始时间', prop: 'startTime', slot: true, width: 130 },
        { label: '结束时间', prop: 'endTime', slot: true, width: 130 },
        { label: '优先级', prop: 'priority', slot: true },
        { label: '文件名', prop: 'programName' },
      ],
      actionOpts: { show: false },
      displayType: '1', // 1 缩略图 2 列表
      displayTypeOpts: [
        {
          value: '1',
          label: '缩略图',
        },
        {
          value: '2',
          label: '详细信息',
        },
      ],
      showDialog: {
        show: false,
      },
      previewDialog: {
        show: false,
      },

      miniContextMenus: [
        { name: '查看' },
        { type: 'divider' },
        { name: '预览' },
      ],

      // 左侧目录树
      folderId: 0,
      ownerUserId: '',
      page: {
        current: 1,
        size: 15,
        total: 0,
      },
      listFetching: false,
      searchVal: '',
      requestOpts: requestOpts,
      // 上传文件列表
      uploadList: [],
      loading: null
    }
  },
  watch: {
    visible(v) {
      if (!v) {
        this.$refs.miniPanel._clearActive()
        this._initSelfList(this.list)
      }
    },
  },
  computed: {},
  created() {
    if(this.requestOpts.corpCode == this.requestOpts.runCorpCode) {
      this.listCols = [
        { label: '开始时间', prop: 'startTime', slot: true, width: 130 },
        { label: '结束时间', prop: 'endTime', slot: true, width: 130 },
        { label: '优先级', prop: 'priority', slot: true },
        { label: '播出时间', prop: 'playTime' },
        { label: '类型', prop: 'type' },
        { label: '插播时间', prop: 'insertPlayTime' },
        { label: '节目名称', prop: 'programName' },
        { label: '注释', prop: 'marks' },
        { label: '节目属性', prop: 'programProperty' },
        { label: '节目长度', prop: 'dateTime' },
        { label: '入点', prop: 'playBeginTime' },
        { label: '出点', prop: 'playEndTime' }
      ]
    }
  },
  methods: {
    ...mapActions(['getTagTree']),
    photoBoxContext(e) {
      this.$refs.miniPanel._contextMenu(e)
    },
    pageChange({ page: current, limit: size }) {
      this.page = {
        ...this.page,
        current: size != this.page.size ? 1 : current,
        size,
      }
      this.fetchList()
    },
    searchHandle() {
      this.page.current = 1
      this.fetchList()
    },
    currentNodeDataChange(data) {
      this.$refs.miniPanel.hideContextMenu()
      console.log('----data', data)
      if (data.id === -1 || data.id === -2) {
        // 下级用户根目录被点击
        this.page.current = 1
        this.page.total = 0
        this.mediaData = []
        return
      } else if (data._isSub || data._isOther) {
        // 下级用户目录被点击
        this.folderId = data && data.id != undefined ? data.id : 0
        if (data.ownerUserId) {
          this.ownerUserId = data.ownerUserId
        } else {
          this.ownerUserId = ''
        }
      } else {
        this.folderId = data ? data.id : 0
        this.ownerUserId = ''
      }
      this.page.current = 1
      this.fetchList()
    },
    getLeftItem() {
      return this.$refs.miniPanel.getActiveItem()
    },
    getRightItem() {
      let items = this.$refs.list.getActiveItem()
      return items.length === 1 ? items[0] : items.length === 0 ? null : items
    },
    ctrl(type) {
      switch (type) {
        case 'add':
          // 添加
          this.addRow(this.getLeftItem())
          break
        case 'remove':
          // 移除
          this.removeRow(this.getRightItem())
          break
        case 'replace':
          this.replaceRow(this.getLeftItem(), this.getRightItem())
          break
        case 'up':
          // 上移
          this.upRow(this.getRightItem())
          break
        case 'down':
          // 下移
          this.downRow(this.getRightItem())
          break
        case 'ok':
          // 确定
          this.$emit(
            'update:list',
            this.self_list.map((item, index) => {
              let o = {
                ...item,
                sortNo: index,
                startTime: item.startTime.join(':'),
                endTime: item.endTime.join(':'),
              }
              delete o._id
              return o
            })
          )
          this.updateVisible(false)
          break
        case 'cancel':
          this.updateVisible(false)
          // 取消
          break
        case 'export':
          this.exportExcel()
          break
        default:
      }
      this.$refs.miniPanel._clearActive()
    },
    updateVisible(v) {
      this.$emit('update:visible', v)
    },
    async getProgramInfo(id, cb) {
      const res = await MediaApi.getProgramInfo({id})
      cb && cb(res)
    },
    beforeUpload(_file) {
      const fileNameSplit = _file.name.split('.')
      const suffix = fileNameSplit[fileNameSplit.length - 1].toUpperCase()
      const suportSuffix = ['XLSX', 'XLS']
      if (suportSuffix.indexOf(suffix) === -1) {
        return false
      }
      return true
    },
    async handleUploadFile(params) {
      const _file = params.raw
      if (!this.beforeUpload(params)) {
        this.$message.error('请上传excel文件')
        return
      }
      const bool = await this.$confirm('提示', `是否要导入${_file.name}`)
      if(!bool) {
        return
      }
      if (this.loading === null) {
        this.loading = this.$loading({
          fullscreen: true,
          text: '正在导入中，请稍微等待',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
      }
      this.doUploadFile(_file)
    },
    async doUploadFile(_file) {
      try {
        const res = await MediaApi.exportProgramFile({ file: _file })
        if(res && res.data) {
          this.addRow(res.data)
        }
        if (this.loading) {
          this.loading.close()
          this.loading = null
        }
      } catch (e) {
        if (this.loading) {
          this.loading.close()
          this.loading = null
        }
      }
    },
    miniContextMenuClicked({ item, option }) {
      switch (option.name) {
        case '查看':
          this.getTagTree(this.getTagTree(this.ownerUserId ? {
            ownerUserIds: [this.ownerUserId]
          } : {_self: true}))
          this.getProgramInfo(item.id, (info) => {
            const copyFile = JSON.parse(JSON.stringify(item))
            this.showDialog = {
              show: true,
              form: {
                ...copyFile,
                ...info
              }
            }
          })
          break
        case '预览':
          this.previewDialog = {
            show: true,
            preData: item,
          }
          break
        default:
      }
    },
    async fetchList() {
      if (this.listFetching) return
      this.listFetching = true
      try {
        const { current, size } = this.page
        const folderId = this.folderId
        const ownerUserId = this.ownerUserId
        let params = {
          folderId,
          current,
          size,
          queryType: 4,
        }
        if (ownerUserId) params.ownerUserId = ownerUserId
        if (this.searchVal) {
          params.queryParam = this.searchVal
        }
        params.auditState = 1
        const res = await MediaApi.getProgram(params)
        console.log(res)
        this.mediaData = res.records.map((item) => {
          item.showType = 'program'
          return {
            ...item,
            // programMedia: item.programMedia
            //   ? item.programMedia.map((i) => {
            //       let mediaArgus = i.mediaArgus
            //       return {
            //         areaId: i.areaId,
            //         mediaArgus: mediaArgus
            //           .filter((m) => m.mediaArgus)
            //           .map((m) => {
            //             try {
            //               let jp = JSON.parse(m.mediaArgus)
            //               return {
            //                 ...jp,
            //               }
            //             } catch (error) {
            //               return {}
            //             }
            //           }),
            //       }
            //     })
            //   : [],
          }
        })
        this.page.total = Number(res.total)
        this.page.current = Number(res.current)
      } catch (error) {
        console.log(error)
      } finally {
        this.listFetching = false
      }
    },
  },
}
</script>

<style lang="scss" scoped>
// import '@/styles/bs-common.scss';

$info-row-h: 57px;
$border-style: 1px solid $bg-e9;
$left-h: 570px;
$left-search-h: 56px;
$left-pag-h: 50px;
$left-main-h: $left-h - $left-search-h - $left-pag-h;

@mixin first-row() {
  height: $left-search-h;
  display: flex;
  align-items: center;
}

.listEditDialog {
  ::v-deep .el-dialog__body {
    padding: 0 !important;
  }

  ::v-deep .el-dialog__header {
    border-bottom: $border-style;
  }
}

.input-280 {
  width: 280px;
}
.input-165 {
  width: 165px;
}
.mr-15 {
  margin-right: 15px;
}
.mr-105 {
  margin-right: 105px;
}

.wrap-box {
  display: flex;
  align-items: stretch;
  padding: 10px;

  .left {
    height: $left-h;
    border: $border-style;

    .picker-box {
      display: flex;
      height: $left-main-h;
      position: relative;
      .menu-box {
        border-right: $border-style;
        width: 184px;
        overflow: auto;
      }
      .photo-box {
        width: 300px;
        overflow: auto;
      }
    }

    .pag-box {
      height: $left-pag-h;
      border-top: $border-style;
      padding-left: 10px;
    }
  }

  .center {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin: 0 15px;
    .el-button {
      width: 45px;
    }
    .el-button + .el-button {
      margin-left: 0;
      margin-top: 10px;
    }
  }

  .right {
    flex: 1;
    height: $left-h;
    border: $border-style;
    .list-area {
      padding: 15px;
      height: 512px;
      width: 525px;
      overflow: auto;
    }
  }
}

.search-row {
  @include first-row();
  padding: 0 10px 0 10px;
  border-bottom: $border-style;

  .search-item {
    display: flex;
    align-items: center;
    .label {
      width: 98px;
    }

    &-title {
      width: 150px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      margin-right: 5px;
    }
    &-label {
      width: 40px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      margin-right: 5px;
    }
  }
}

.list-title-row {
  @include first-row();
  justify-content: space-between;
  padding-left: 18px;
  border-bottom: $border-style;
  .button-row {
    margin-right: 18px;
  }
}

.el-button--small {
  min-width: 45px;
  min-height: 28px;
  height: 28px;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}
::v-deep .el-button--small i {
  padding-right: 0 !important;
}
.el-input__suffix {
  top: 4px;
}
</style>